import 'dart:convert';

import 'package:flutter/material.dart';

NodeBean nodeBeanFromJson(String str) => NodeBean.fromMap(json.decode(str));

String nodeBeanToJson(NodeBean data) => json.encode(data.toMap());

class NodeBean<T> {
  /// 当前节点id
  String? id;

  /// 父节点id
  String? pid;

  /// 节点数据实体类
  T? data;

  /// 节点名称
  String? name;

  dynamic community;

  /// 当前的级别
  int? level;

  /// 是否展开
  bool isExpand;

  IconData? icon;

  /// 下一级的子Node
  List<NodeBean<T>> children = [];

  /// 是否被checked选中
  bool isChecked;

  /// 设置开启 关闭的图片
  IconData iconExpand = Icons.keyboard_arrow_down, iconCollapse = Icons.arrow_forward_ios;

  NodeBean({
    this.id,
    this.pid,
    this.data,
    this.name,
    required this.community,
    this.level,
    this.isExpand = false,
    this.icon,
    required this.children,
    this.isChecked = false,
  });

  factory NodeBean.fromMap(Map<String, dynamic> json) => NodeBean(
    id: json["id"],
    community: json["community"],
    name: json["name"],
    children: List<NodeBean<T>>.from(json["children"].map((x) => NodeBean.fromMap(x))),
    pid: json["pid"],
  );

  Map<String, dynamic> toMap() => {
    "id": id,
    "name": name,
    "children": List<NodeBean<T>>.from(children.map((x) => x.toMap())),
    "pid": pid,
  };

  /// 是否是叶子节点
  bool isLeaf() {
    return getChildren().isEmpty;
  }

  /// 设置展开
  setExpand(bool isExpand) {
    this.isExpand = isExpand;
    if (!isExpand) {
      for (var node in children) {
        node.setExpand(isExpand);
      }
    }
  }

  List<NodeBean<T>> getChildren() {
    return children;
  }

  void setIcon(IconData icon) {
    this.icon = icon;
  }

  getLevel() {
    return this.level;
  }

  void setLevel(int level) {
    this.level = level;
  }
}